var SCRIBEFIRE_NOTES = {
	notesFile : "performancing-notes.xml",
	notesArchiveFile : "performancing-notes-old.xml",
	
	init : function () {
		var db = SCRIBEFIRE_DB.getDB();
		
		var notesXML = this.getNotesXML();
		
		if (notesXML) {
			var notes = notesXML.notes;
		
			// Load the notes into the note list
			for (var j = 0; j < notes.children().length(); j++) {
				try {
					var title = notes.note[j].title.toString();
					title = title.replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "");
					var content = notes.note[j].content.toString();
					var modified = new Date(notes.note[j].datemodified.toString());
			
					var insert = db.createStatement("INSERT INTO "+SCRIBEFIRE_DB.notesTable+" (title, content, modified) VALUES (?1, ?2, ?3)");
					insert.bindUTF8StringParameter(0, title);
					insert.bindUTF8StringParameter(1, content);
					insert.bindInt64Parameter(2, modified.getTime());
			
					insert.execute();
				} catch (ignoreThis) {
					
				}
			}
			
			// Move the file out of the way.
			var file = gPerformancingUtil.getFilePath(this.notesArchiveFile, true);
			PerFormancingFileIO.write(file, notesXML.toString(), "w", "UTF-8");
			
			// Delete the old file and filename.
			var oldFile = gPerformancingUtil.getFilePath(this.notesFile);
			PerFormancingFileIO.unlink(oldFile);
		}
		
		SCRIBEFIRE_DB.closeDB(db);
		
		this.loadNotes();
	},
	
	/* Used only for upgrade to SQLite storage. */
	
	getNotesXML : function () {
		var file = gPerformancingUtil.getFilePath(this.notesFile);

	    var theXMLString = PerFormancingFileIO.read(file, "UTF-8");

		if (!theXMLString) {
			return false;
		}
    
		try {
	    	var theNotesXML = new XML(theXMLString);
		} catch (e) {
			return false;
		}
	
		return theNotesXML;
	},
	
	loadNotes : function (searchString) {
		var db = SCRIBEFIRE_DB.getDB();
		
		var sql = "SELECT id, title, content, modified FROM "+SCRIBEFIRE_DB.notesTable+" ";
		
		if (searchString) {
			sql += " WHERE title LIKE ?1 OR content LIKE ?1 ";
		}
		
		sql += " ORDER BY modified DESC";
		
		var select = db.createStatement(sql);
		
		if (searchString) {
			select.bindUTF8StringParameter(0, '%'+searchString+'%');
		}
		
		gPerformancingUtil.clearListOut('scribefire-notes-list');
		
		var list = document.getElementById('scribefire-notes-list');
		
		try {
			while (select.executeStep()) {
				var guid = select.getInt32(0);
				var title = select.getUTF8String(1);
				
				title = title.replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "");
				
				if (!title) {
					title = performancingUI.getLocaleString("untitledNote");
				}
				
				var content = select.getUTF8String(2);
				var modified = select.getInt64(3);
				
			    var item = document.createElement('richlistitem');
			    item.setAttribute('id', 'note-' + guid);
			    item.setAttribute('noteGUID', guid);
			    item.setAttribute('date', modified);
			    item.setAttribute('onclick', "SCRIBEFIRE_NOTES.addNoteToEditor(this, event);");
			    item.setAttribute('class', "performancenote");
				item.setAttribute("postid", guid);
				
				var label = document.createElement("label");
				label.setAttribute("value", title);
				item.appendChild(label);

			    list.appendChild(item);
			}
		} catch (e) {
			SFLOG(e);
		} finally {
			select.reset();
		}
		
		SCRIBEFIRE_DB.closeDB(db);
	},
	
	doSave : function () {
    	this.reSaveNote(true);
	},
	
	reSaveNote : function (newNote){
	    var title = performancingEditor.getTitle();
		var content = performancingEditor.getContent();
	    var date = new Date().getTime();
		
		var db = SCRIBEFIRE_DB.getDB();

		if (newNote) {
			var query = db.createStatement("INSERT INTO "+SCRIBEFIRE_DB.notesTable+" (title, content, modified) VALUES (?1, ?2, ?3)");
		}
		else {
			var guid = performancingEditor.getCurrentEditorWindow().pffEditorUI.entryId;
			var query = db.createStatement("UPDATE "+SCRIBEFIRE_DB.notesTable+" SET title=?1, content=?2, modified=?3 WHERE id=?4");
			query.bindInt32Parameter(3, guid);
		}
		
		query.bindUTF8StringParameter(0, title);
		query.bindUTF8StringParameter(1, content);
		query.bindInt64Parameter(2, date);
		
		query.execute();
		
		if (newNote) {
			var guid = db.lastInsertRowID;
			performancingEditor.setEntryType("note");
			performancingEditor.setEntryId(guid);
		}
		
		SCRIBEFIRE_DB.closeDB(db);
		
		// Now reload notes
		this.loadNotes();
	},
	
	addNoteToEditor : function (theElement, event){
		if (event.ctrlKey || event.metaKey || event.shiftKey) {
			return;
		}
		
		SF_MOB.toolbarButtonPress(0);
		
		// First check if the item is already open.
		if (!performancingEditor.selectTabForEntry("note", theElement.getAttribute("noteGUID")) && document.getElementById("scribefire-notes-list").selectedCount <= 1) {
			performancingEditor.newTab(true);
			setTimeout(function () {
				performancingEditor.newTab(true, function (x) { SCRIBEFIRE_NOTES.continueAddNoteToEditor(x); }, theElement);
			}, 1000);
		}
	},
	
	continueAddNoteToEditor : function (theElement) {
		var guid = theElement.getAttribute("noteGUID");
		
		var db = SCRIBEFIRE_DB.getDB();
		var select = db.createStatement("SELECT title, content FROM "+SCRIBEFIRE_DB.notesTable+" WHERE id=?1");
		select.bindInt32Parameter(0, guid);
		
		try {
			while (select.executeStep()) {
				var title = select.getUTF8String(0);
				var content = select.getUTF8String(1);
				
				performancingEditor.setContent(content);
				performancingEditor.setTitle(title);

				performancingEditor.setEntryType("note");
				performancingEditor.setEntryId(guid);

				break;
			}
		} catch (e) {
		} finally {
			select.reset();
		}
		
		SCRIBEFIRE_DB.closeDB(db);
		
		return true;
	},
	
	deleteSelectedNotes : function () {
		var prompt = (document.getElementById("scribefire-notes-list").selectedCount > 1) ? performancingUI.getLocaleString("deletenotes") : performancingUI.getLocaleString("deletenote");
		
		if (confirm(prompt)) {
			var db = SCRIBEFIRE_DB.getDB();
			
			var selectedTab = [ performancingEditor.getEntryType(), performancingEditor.getEntryId() ];
			
			var notes = document.getElementById("scribefire-notes-list").selectedItems;
			
			var guids = [];
			
			for (var i = 0; i < notes.length; i++) {
				guids.push(notes[i].getAttribute("noteGUID"));
			}
			
			for (var i = 0; i < guids.length; i++) {
				var del = db.createStatement("DELETE FROM "+SCRIBEFIRE_DB.notesTable+" WHERE id=?1");
				del.bindInt32Parameter(0, guids[i]);
				del.execute();
				del.reset();
				
				if (performancingEditor.selectTabForEntry('note', guids[i])) {
					performancingEditor.closeTab(true);
				}
			}
			
			SCRIBEFIRE_DB.closeDB(db);
			
			try {
				performancingEditor.selectTabForEntry(selectedTab[0], selectedTab[1]);
			} catch (selectedWasDeleted) {
			}
			
			this.loadNotes();
		}
	},
	
	deleteNoteEntry : function () {
		if (confirm(performancingUI.getLocaleString("deletenote"))) {
			var db = SCRIBEFIRE_DB.getDB();
			
			var guid = performancingEditor.getEntryId();
			
			var del = db.createStatement("DELETE FROM "+SCRIBEFIRE_DB.notesTable+" WHERE id=?1");
			del.bindInt32Parameter(0, guid);
			del.execute();
			
			SCRIBEFIRE_DB.closeDB(db);
			
			performancingEditor.closeTab(true);
			performancingUI.clearTechnoratiTags();
			this.loadNotes();
		}
	}
};